<template>
  <el-dialog ref="wkDialog" :visible="visible" :append-to-body="true" :close-on-click-modal="false" width="700px"
             @close="handleCancel">
    <span slot="title" class="el-dialog__title">
      {{ title }}
      <i v-if="helpObj" class="wk wk-icon-fill-help wk-help-tips" :data-type="helpObj.dataType"
         :data-id="helpObj.dataId"/>
    </span>
    <div class="form-add-dialog-body">
      <create-sections title="岗位信息">
        <el-form ref="crmPostForm" :model="postFieldForm" :rules="postFieldRules" :validate-on-rule-change="false"
                 class="wk-form"
                 label-position="top">
          <wk-form-item v-if="authPostFields.includes(item.fieldName)" v-for="(item, index) in postFieldList"
                        :key="index" :index="index" :field-from="postFieldForm"
                        :item="item" :disabled="item.disabled" style-percent="50%" @change="postFormChange">
            <template slot-scope="{ data }">
              <v-distpicker v-if="data && data.formType == 'area' || data.formType == 'city'"
                            :province="postFieldForm[data.field].province" :city="postFieldForm[data.field].city"
                            :disabled="data.disabled"
                            hide-area @province="postSelectProvince($event, data)"
                            @city="postSelectCity($event, data)"/>
            </template>
          </wk-form-item>
        </el-form>
        <slot/>
      </create-sections>
      <create-sections title="基本信息">
        <el-form ref="crmBaseForm" :model="baseFieldForm" :rules="baseFieldRules" :validate-on-rule-change="false"
                 class="wk-form"
                 label-position="top">
          <wk-form-item v-if="authBaseFields.includes(item.fieldName)" v-for="(item, index) in baseFieldList"
                        :key="index" :index="index" :field-from="baseFieldForm"
                        :item="item" :disabled="item.disabled" style-percent="50%" @change="baseFormChange">
            <template slot-scope="{ data }">
              <v-distpicker v-if="data && data.formType == 'area' || data.formType == 'city'"
                            :province="baseFieldForm[data.field].province" :city="baseFieldForm[data.field].city"
                            :disabled="data.disabled"
                            hide-area @province="baseSelectProvince($event, data)"
                            @city="baseSelectCity($event, data)"/>
            </template>
          </wk-form-item>
        </el-form>
        <slot/>
      </create-sections>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button v-debounce="handleConfirm" type="primary">保存</el-button>
      <el-button @click.native="handleCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  hrmEmployeeFieldVerifyAPI
} from '@/api/hrm/employee'

import WkFormItem from '@/components/NewCom/WkForm/WkFormItem'

import ElDialogLoadingMixin from '@/mixins/ElDialogLoading'
import CustomFieldsMixin from '@/mixins/CustomFields'
import VDistpicker from '@/components/VDistpicker'
import CreateSections from "@/components/CreateSections.vue";

export default {

  // 自定义字段弹窗新建
  name: 'CustomFormAddDialog',
  components: {
    WkFormItem,
    VDistpicker,
    CreateSections,
  },
  mixins: [ElDialogLoadingMixin, CustomFieldsMixin],
  props: {
    id: [String, Number],
    title: String,
    postFields: Array,
    baseFields: Array,
    helpObj: Object,
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    isExamine: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      authPostFields: ["join_company_time", "work_forms", "dept", "org"],
      authBaseFields: ["id_number", "nation", "sex", "date_of_birth", "employee_name", "join_company_time", "join_work_time", "source"],
      loading: false,
      postFieldList: [],
      baseFieldList: [],
      postFieldForm: {},
      baseFieldForm: {},
      postFieldRules: {},
      baseFieldRules: {},
      tempPolTimeObject: {}
    }
  },
  computed: {},
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getPostField()
          this.getBaseField()
        }
      },
      immediate: true
    },
    baseFieldForm: {
      handler() {
        if (this.baseFieldForm.pol_id === '群众' || this.baseFieldForm.pol_id === '团员') {
          const index = this.baseFieldList.findIndex(item => item.fieldName === 'pol_time');
          if (index !== -1) {
            this.baseFieldList.splice(index, 1);
            this.baseFieldForm.pol_time = null;
          }
        } else {
          const index = this.baseFieldList.findIndex(item => item.fieldName === 'pol_time');
          if (index === -1) {
            this.baseFieldList.splice(3, 0, this.tempPolTimeObject)
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    /**
     * 获取数据
     */
    getPostField() {
      const list = this.postFields
      const assistIds = this.getFormAssistIds(list)

      const fieldList = []
      const fieldRules = {}
      const fieldForm = {}
      list.forEach(item => {
        const temp = this.getFormItemDefaultProperty(item, false)
        temp.show = !assistIds.includes(item.formAssistId)

        // 是否能编辑权限
        if (temp.show) {
          fieldRules[temp.field] = this.getRules(item)
        }

        // 是否可编辑
        if (!temp.hasOwnProperty('disabled')) {
          temp.disabled = false
        }

        // 特殊字段允许多选
        if (typeof temp.radio !== 'boolean') {
          this.getItemRadio(item, temp)
        }

        // 获取默认值
        if (temp.show) {
          fieldForm[temp.field] = this.getItemValue(item, null, this.id ? 'update' : 'save')
        }
        fieldList.push(temp)
      })

      this.postFieldList = fieldList
      this.postFieldForm = fieldForm
      this.postFieldRules = fieldRules
    },

    /**
     * 获取数据
     */
    getBaseField() {
      const list = this.baseFields
      const assistIds = this.getFormAssistIds(list)

      const fieldList = []
      const fieldRules = {}
      const fieldForm = {}
      list.forEach(item => {
        const temp = this.getFormItemDefaultProperty(item, false)
        temp.show = !assistIds.includes(item.formAssistId)

        // 是否能编辑权限
        if (temp.show) {
          fieldRules[temp.field] = this.getRules(item)
        }

        // 是否可编辑
        if (!temp.hasOwnProperty('disabled')) {
          temp.disabled = false
        }

        // 特殊字段允许多选
        if (typeof temp.radio !== 'boolean') {
          this.getItemRadio(item, temp)
        }

        // 获取默认值
        if (temp.show) {
          fieldForm[temp.field] = this.getItemValue(item, null, this.id ? 'update' : 'save')
        }
        fieldList.push(temp)
      })

      this.baseFieldList = fieldList
      this.baseFieldForm = fieldForm
      this.baseFieldRules = fieldRules
      const index = this.baseFieldList.findIndex(item => item.fieldName === 'pol_time');
      if (index !== -1) {
        this.tempPolTimeObject = this.baseFieldList[index];
      }
    },

    /**
     * 验证唯一
     */
    UniquePromise({field, value}) {
      // this.action 详情
      return this.getUniquePromise(field, value, this.action)
    },

    /**
     * 验证唯一
     */
    getUniquePromise(field, value, detail) {
      return new Promise((resolve, reject) => {
        var validatesParams = {}
        validatesParams.fieldId = field.fieldId
        validatesParams.id = this.id
        validatesParams.value = this.getRealParams(field, value)

        hrmEmployeeFieldVerifyAPI(validatesParams).then(res => {
          // status 1 通过 0
          const resData = res.data || {}
          if (resData.status === 1) {
            resolve()
          } else {
            reject(`${field.name}已存在`)
          }
        }).catch(() => {
          reject()
        })
      })
    },

    /**
     * 取消选择
     */
    handleCancel() {
      this.$emit('update:visible', false)
    },

    /**
     * 点击确定
     */
    async handleConfirm() {
      const crmPostForm = this.$refs.crmPostForm;
      const crmBaseForm = this.$refs.crmBaseForm;
      if (!crmPostForm) {
        console.error('crmPostForm is undefined');
        return;
      }
      if (!crmBaseForm) {
        console.error('crmBaseForm is undefined');
        return;
      }
      if (!(await this.validateForm(crmPostForm))) {
        return;
      }
      if (!(await this.validateForm(crmBaseForm))) {
        return;
      }
      const postParams = this.getSubmiteParams(
          [].concat.apply([], this.postFieldList),
          this.postFieldForm,
          ['isFixed']
      );
      const baseParams = this.getSubmiteParams(
          [].concat.apply([], this.baseFieldList),
          this.baseFieldForm,
          ['isFixed']
      );
      postParams.isExamine = this.isExamine;
      baseParams.isExamine = this.isExamine;
      this.$emit('pass', {baseParams, postParams});
    },

    // 封装表单验证逻辑
    async validateForm(form) {
      return new Promise((resolve) => {
        form.validate(valid => {
          if (valid) {
            resolve(true); // 表单验证通过
          } else {
            this.getFormErrorMessage(form); // 显示错误消息
            resolve(false); // 表单验证失败
          }
        });
      });
    },

    /**
     * change 事件
     */
    postFormChange(field, index, value, valueList) {
      if ([
            'select',
            'checkbox'
          ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const {fieldForm, fieldRules} = this.getFormContentByOptionsChange(this.postFieldList, this.postFieldForm)
        this.postFieldForm = fieldForm
        this.fieldRules = fieldRules
      }

      if (field.name == '身份证号' && value.length == 18) {
        var genderCode = value.substring(16, 17);
        let sexs = genderCode % 2 === 0 ? "女" : "男"
        let data = this.postFieldList.find(o => {
          return o.name == '性别'
        })
        let sex = data.setting.find(o => {
          return o.name == sexs
        })
        if (data) {
          this.postFieldForm[data.fieldName] = sex.value
        }

        let birthDay = value.substr(6, 4) + "-" + value.substr(10, 2) + "-" + value.substr(12, 2);
        let birth = this.postFieldList.find(o => {
          return o.name == '出生日期'
        })
        if (birth) {
          this.postFieldForm[birth.fieldName] = birthDay
        }
      }
    },

    /**
     * change 事件
     */
    baseFormChange(field, index, value, valueList) {
      if ([
            'select',
            'checkbox'
          ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const {fieldForm, fieldRules} = this.getFormContentByOptionsChange(this.baseFieldList, this.baseFieldForm)
        this.baseFieldForm = fieldForm
        this.fieldRules = fieldRules
      }

      if (field.name == '身份证号' && value.length == 18) {
        var genderCode = value.substring(16, 17);
        let sexs = genderCode % 2 === 0 ? "女" : "男"
        let data = this.baseFieldList.find(o => {
          return o.name == '性别'
        })
        let sex = data.setting.find(o => {
          return o.name == sexs
        })
        if (data) {
          this.baseFieldForm[data.fieldName] = sex.value
        }

        let birthDay = value.substr(6, 4) + "-" + value.substr(10, 2) + "-" + value.substr(12, 2);
        let birth = this.baseFieldList.find(o => {
          return o.name == '出生日期'
        })
        if (birth) {
          this.baseFieldForm[birth.fieldName] = birthDay
        }
      }
    },

    /**
     * 选择省市
     */
    postSelectProvince(data, item) {
      this.postFieldForm[item.field].province = data.value
    },

    postSelectCity(data, item) {
      this.postFieldForm[item.field].city = data.value
    },

    /**
     * 选择省市
     */
    baseSelectProvince(data, item) {
      this.baseFieldForm[item.field].province = data.value
    },

    baseSelectCity(data, item) {
      this.baseFieldForm[item.field].city = data.value
    }
  }
}
</script>

<style lang="scss" scoped>
.form-add-dialog-body {
  max-height: 55vh;
  overflow-x: hidden;
  overflow-y: auto;

  .wk-form {
    display: flex;
    flex-wrap: wrap;

    ::v-deep.is-detail_table {
      width: 100% !important;
    }
  }
}
</style>
